import { Component, OnInit, Output, EventEmitter, Input } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { StaffsService } from 'src/app/shared/services/http/staffs.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { StaffDto } from 'src/app/shared/services/http/dto/staff.dto';

@Component({
  selector: 'app-edit-staff-form',
  templateUrl: './edit-staff-form.component.html',
  styleUrls: ['./edit-staff-form.component.css'],
})
export class EditStaffFormComponent implements OnInit {
  // 员工表单
  staffForm: FormGroup = this.formBuilder.group({
    account: [''],
    password: [''],
  });

  // 按钮是否被禁止
  disabled = false;

  // 要编辑的员工
  // tslint:disable-next-line: variable-name
  private _staff: StaffDto;

  // _id
  // tslint:disable-next-line: variable-name
  _id = '';

  // 更新成功事件
  @Output() update = new EventEmitter();

  @Input()
  set staff(staff: StaffDto) {
    this._staff = staff;

    if (staff) {
      const { _id } = staff;
      this._id = _id;
      this.staffForm = this.formBuilder.group({
        password: [''],
      });
    }
  }

  get staff() {
    return this._staff;
  }

  constructor(
    private formBuilder: FormBuilder,
    private staffsService: StaffsService,
    private message: NzMessageService
  ) {}

  ngOnInit(): void {}

  /**
   * 提交编辑员工
   * @param staffDto 员工
   */
  onSubmit({ password }: { password: string }) {
    this.disabled = true;
    this.staffsService.updatePassword(this._id, password).subscribe(() => {
      this.message.create('success', `修改员工成功`);
      this.disabled = false;
      this.update.emit();
    });
  }
}
